package com.document.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.document.common.exception.SoException;
import com.document.common.utils.*;
import com.document.dao.FileManageMapper;
import com.document.entity.po.FileManageEntity;
import com.document.entity.request.FileManageRequest;
import com.document.service.iservice.FileManageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class FileManageServiceImpl implements FileManageService {

    @Autowired
    private FileManageMapper fileManageMapper;

    @Override
    public IPage<FileManageEntity> queryAll(FileManageRequest request) {
        Page<FileManageEntity> page = new Page<>(request.getPageNum(),request.getPageSize());
        //查询总记录数
        page.setSearchCount(true);
        QueryWrapper<FileManageEntity> wrapper = new QueryWrapper<FileManageEntity>()
                .eq(StringUtil.isNotEmpty(request.getId()),"id",request.getId())
                .eq(null != request.getFileType(),"file_type",request.getFileType())
                .like(StringUtil.isNotEmpty(request.getFileName()),"file_name",request.getFileName())
                .orderByDesc("create_time");
        IPage<FileManageEntity> pageResponse = fileManageMapper.selectPage(page,wrapper);
        if(null != pageResponse.getRecords() && pageResponse.getRecords().size() >0){
            for(FileManageEntity item : pageResponse.getRecords()){
                item.setFilePath("");
            }
            // 如果不是管理员，查找它创建的以及共享的
            if(!AuthUserToken.isAdmin()){
                String userName = AuthUserToken.getUserName();
                List<FileManageEntity> collect = pageResponse.getRecords().stream().filter(p -> userName.equals(p.getCreateUserName())
                        || 0 == p.getFileStatus()).collect(Collectors.toList());
                pageResponse.setRecords(collect);
            }
        }
        return pageResponse;
    }

    @Override
    public void deleteById(String[] ids) {
        List<String> errorList = new ArrayList<>();
        for(String id : ids){
            // 如果不是管理员，并且不是它创建的文件无法删除
            if(!AuthUserToken.isAdmin()){
                FileManageEntity fileManageEntity = fileManageMapper.selectById(id);
                if(!AuthUserToken.getUserName().equals(fileManageEntity.getCreateUserName())){
                    errorList.add(id);
                    continue;
                }
            }
            fileManageMapper.deleteById(id);
        }
        if(errorList != null && errorList.size() >0){
            String errorStr = JSONObject.toJSONString(errorList);
            throw new SoException("以下文件删除失败："+errorStr);
        }
    }

    @Override
    public int save(FileManageRequest request) {
        FileManageEntity bean = BeanUtils.copy(request, FileManageEntity.class);
        // 重复性校验
        QueryWrapper<FileManageEntity> wrapper = new QueryWrapper<FileManageEntity>()
                .eq("file_name",bean.getFileName());
        List<FileManageEntity> repeatList = fileManageMapper.selectList(wrapper);
        if(repeatList != null && repeatList.size() > 0){
            throw new SoException("文件名不能重复！");
        }
        bean.setId(UUIDUtils.UUIDReplace());
        bean.setCreateTime(new Date());
        bean.setCreateUserName(AuthUserToken.getUserName());
        // 如果用户输入密码。进行MD5加密
        if(StringUtil.isNotBlank(request.getFilePassword())){
            bean.setFilePassword(MD5Utils.getMd5(request.getFilePassword()));
        }
        return fileManageMapper.insert(bean);
    }

    @Override
    public int update(FileManageRequest request) {
        FileManageEntity bean = BeanUtils.copy(request, FileManageEntity.class);
        // 重复性校验
        QueryWrapper<FileManageEntity> wrapper = new QueryWrapper<FileManageEntity>()
                .eq("file_name",bean.getFileName())
                .ne("id",bean.getId());
        List<FileManageEntity> repeatList = fileManageMapper.selectList(wrapper);
        if(repeatList != null && repeatList.size() > 0){
            throw new SoException("文件名不能重复！");
        }
        return fileManageMapper.updateById(bean);
    }

    @Override
    public FileManageEntity selectOneById(FileManageRequest request) {
        FileManageEntity fileManageEntity = fileManageMapper.selectById(request.getId());
        return fileManageEntity;
    }

    @Override
    public FileManageEntity review(FileManageRequest request) {
        // 先核对密码
        FileManageEntity fileManageEntity = fileManageMapper.selectById(request.getId());
        if(StringUtil.isNotBlank(fileManageEntity.getFilePassword())){
            String md5 = MD5Utils.getMd5(request.getFilePassword());
            // 密码验证不通过
            if(!md5.equals(fileManageEntity.getFilePassword())){
                throw new SoException("文件密码不正确");
            }
        }
        String filePath ="";
        try {
            String path = "http://oss.xianyum.cn/"+fileManageEntity.getFilePath();
			fileManageEntity.setFileUrl(path);
            // url需要编码才能在线浏览
            filePath ="https://view.officeapps.live.com/op/view.aspx?src="+URLEncoder.encode(path,"UTF-8");
        }catch (Exception e){
            log.error(e.getMessage());
            throw new SoException("url编码异常");
        }
        fileManageEntity.setFilePath(filePath);
        return fileManageEntity;
    }
}
